<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

// turn off magic_quotes_runtime
set_magic_quotes_runtime(0);

// exceptions
class Sigma_Exception extends Exception
{
	public function __construct($message, $code = 0)
	{
		if (!headers_sent()) {
			header('HTTP/1.1 503 Temporary Unavailable');
		}
		parent::__construct($message, $code);
	}
}

/**
 * If it is needed, removes quotes
 *
 * @param string $string
 * @return string
 */
function _undoQuotes($string) {
	return get_magic_quotes_gpc() ? (is_array($string) ? array_map('_undoQuotes',$string) : stripslashes($string)) : $string;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _get($name = NULL) {
	if (!$name) return array_map('_undoQuotes',$_GET);

	if (array_key_exists($name,$_GET)) {
		if (is_array($_GET[$name]))
			return array_map('_undoQuotes',$_GET[$name]);
		else
			return _undoQuotes($_GET[$name]);
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _post($name = NULL) {
	if (!$name) return array_map('_undoQuotes',$_POST);

	if (array_key_exists($name,$_POST)) {
		if (is_array($_POST[$name]))
			return array_map('_undoQuotes',$_POST[$name]);
		else
			return _undoQuotes($_POST[$name]);
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _cookie($name = NULL) {
	if (!$name) return array_map('_undoQuotes',$_COOKIE);

	if (array_key_exists($name,$_COOKIE)) {
		if (is_array($_COOKIE[$name]))
			return array_map('_undoQuotes',$_COOKIE[$name]);
		else
			return _undoQuotes($_COOKIE[$name]);
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _session($name = NULL) {
	if (!$name) return array_map('_undoQuotes',$_SESSION);

	if (array_key_exists($name,(array) $_SESSION)) {
		if (is_array($_SESSION[$name]))
			return array_map('_undoQuotes',$_SESSION[$name]);
		else
			return _undoQuotes($_SESSION[$name]);
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _server($name) {
	if (array_key_exists($name,$_SERVER)) {
		return $_SERVER[$name];
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _env($name) {
	if (array_key_exists($name,$_ENV)) {
		return $_ENV[$name];
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key
 *
 * @param string $name
 * @return string
 */
function _files($name) {
	if (array_key_exists($name,$_FILES)) {
		return $_FILES[$name];
	}
	return NULL;
}

/**
 * Returns superglobal array with specified key in order: EGPCS
 *
 * @param string $name
 * @return string
 */
function _request($name) {
	if (array_key_exists($name,$_ENV)) {
        return _env($name);
	} else if (array_key_exists($name,$_GET)) {
        return _get($name);
	} else if (array_key_exists($name,$_POST)) {
        return _post($name);
	} else if (array_key_exists($name,$_COOKIE)) {
		return _cookie($name);
	} else if (array_key_exists($name,$_SERVER)) {
		return _server($name);
	} else if (array_key_exists($name,$_REQUEST)) {
		return _undoQuotes($_REQUEST[$name]);
	}
	return NULL;
}

/**
 * Convert some XHTML characters to entities
 *
 * @return string
 */
function _hsc($string, $quoteStyle = ENT_QUOTES, $charset = 'UTF-8', $doubleEncode = true) {
	if (version_compare(PHP_VERSION,'5.2.3','>=')) {
		return htmlspecialchars($string, $quoteStyle, $charset, $doubleEncode);
	} else {
		return htmlspecialchars($string, $quoteStyle, $charset);
	}
}

/**
 * Real IP address of visitor
 *
 * @link http://php.net/
 * @return string
 */
function _ip() {
	$ip = false;

	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
		$ip = _server('HTTP_CLIENT_IP');
	}

	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$ips = explode(', ',_server('HTTP_X_FORWARDED_FOR'));

		if ($ip) {
			array_unshift($ips,$ip);
			$ip = false;
		}

		for ($i = 0; $i < count($ips); $i++) {
			if (!preg_match('/^(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\./',$ips[$i])) {
				if (ip2long($ips[$i]) != false) {
					$ip = $ips[$i];
					break;
				}
			}
		}
	}

	return $ip ? $ip : _hsc(_server('REMOTE_ADDR'));
}

/**
 * SEO URL
 * 
 * @param string $url
 * @return string
 */
function _url($url) {
	// remove diacritics
	$url = str_replace(
	array('Á','Ą','Ä','Å','Æ','Ć','Č','Ç','Ď','Đ','Ê','È','É','Ě','Ë','Ì','Í','Î','Ï','Ĺ','Ľ','Ł','Ň','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ŕ','Ř','Ś','Š','Ş','Ť','Ţ','Ù','Ú','Ů','Û','Ü','Ý','Ź','Ž','Ż','à','á','ą','ä','â','ã','å','æ','ć','č','ç','ď','đ','è','é','ě','ê','ë','ę','ì','í','î','ï','ĺ','ľ','ł','ń','ň','ñ','ò','ó','ô','õ','ø','ö','ŕ','ř','ś','š','ş','ť','ţ','ù','ú','ů','û','ü','ý','ÿ','ź','ž','ż','ß' ,'Þ', 'þ'),
	array('a','a','a','a','a','c','c','c','d','d','e','e','e','e','e','i','i','i','i','l','l','l','n','n','o','o','o','o','o','o','r','r','s','s','s','t','t','u','u','u','u','u','y','z','z','z','a','a','a','a','a','a','a','a','c','c','c','d','d','e','e','e','e','e','e','i','i','i','i','l','l','i','n','n','n','o','o','o','o','o','o','r','r','s','s','s','t','t','u','u','u','u','u','y','y','z','z','z','ss','th','th'),
	$url);

	// remove entities
	$url = htmlentities($url,ENT_QUOTES,'UTF-8');
	$url = preg_replace('/&#?([a-z0-9]+);/i',NULL,$url);

	// convert to small characters
	$url = strtolower($url);

	// remove unwanted characters
	$url = preg_replace('/[^a-z0-9_\-\. ]+/i',NULL,$url);

	// change some characters to dashes
	$url = preg_replace('/(_|-|\.|\s)+/','-',$url);

	// remove dashes from the beginning end the ending
	$url = trim($url,'-');

	return $url;
}
